﻿using System;
using System.Web;

using DQS.Core.Log;

/// <summary>
/// 全局异常处理
/// </summary>
public class ErrorModule : IHttpModule
{
    public ErrorModule() { }

    public void Init(HttpApplication context)
    {
        context.Error += new EventHandler(ShowError);
    }
    
    public void Dispose() { }

    private void ShowError(object sender, EventArgs e)
    {
        HttpContext context = HttpContext.Current;
        Exception ex = context.Server.GetLastError();
        string errorCode = Guid.NewGuid().ToString();
        String errorMsg = ex.InnerException == null ? ex.Message : ex.InnerException.Message;        
        Log.Instance(this).Error(BuildErrorString(errorCode, context));        
        context.Server.ClearError();
        context.Response.Redirect("~/Error.aspx?ErrorCode=" + errorCode + "&ErrorInfo=" + errorMsg);
    }

    private static string BuildErrorString(string errorCode, HttpContext context)
    {        
        Exception ex = context.Server.GetLastError();
        String errorStr = String.Empty;
        if (ex != null)
        {
            errorStr = "{ErrorCode:" + errorCode
                + ",ErrorPage:" + context.Request.Url.ToString()
                + ",ErrorMsg:" + ex.GetBaseException().Message
                + ",StackTrace:" + ex.StackTrace;
            if (ex.InnerException != null)
            {
                errorStr = errorStr + ",InnerErrorMsg:" + ex.InnerException.Message + ",InnerStackTrace:"
                    + ex.InnerException.StackTrace;
            }
            errorStr += "}";
        }
        return errorStr;
    }
}
